﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using Corsat.Library;
using Corsat.Library.DataManager;

namespace Corsat.Web._2013
{
    public partial class Profile : System.Web.UI.Page
    {
        public int AccountId
        {
            get
            {
                int id = 0;
                if (Session["accountId"] != null)
                {
                    int.TryParse(Session["accountId"].ToString(), out id);
                }
                return id;
            }
        }
        public bool PassTechExam
        {
            get
            {
                if (Session["passTechExam"] != null)
                {
                    return bool.Parse(Session["passTechExam"].ToString());
                }
                return false;
            }
            set { Session["passTechExam"] = value; }
        }

        public bool EnableExam
        {
            get
            {
                bool value = false;
                if (WebConfigurationManager.AppSettings["enableOnlineExams"] != null)
                {
                    bool.TryParse(WebConfigurationManager.AppSettings["enableOnlineExams"], out value);
                }
                return value;
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                PassTechExam = false;
                // Load Technology Course names
                List<Library.Item> CourseNames = Main.GetAllItemsByCategory(Category.TechnologyCourses);
                CourseNames.Insert(0, new Library.Item() { Value = "اختر كورس" });
                ddlCourseNames.DataSource = CourseNames;
                ddlCourseNames.DataTextField = "Value";
                ddlCourseNames.DataValueField = "Id";
                ddlCourseNames.DataBind();

                //Session["accountId"] = 3020;
                if (AccountId > 0)
                {
                    LoadAccount();
                }
                else
                {
                    Response.Redirect("DefaultPage.aspx");
                }
            }

        }

        private void LoadAccount()
        {
            var account = Main.GetAccountById(AccountId);
            lblName.Text = account.ArabicName;
            lblAccountId.Text = account.CorsatId.ToString();
            lblSsn.Text = account.SSN;

            if (account.Diocese.Id != 0)
                lblDiocese.Text = account.Diocese.Value;

            if (account.Church.Id != 0)
            {
                lblChurch.Text = account.Church.Value;
            }
            if (account.TechnologyCourse.Course.Id != 0)
            {
                btnReservePopup.Visible = false;
                lblTechCourseName.Text = account.TechnologyCourse.Course.Value;

                lblTechCourseExamResrvationDate.Text = account.TechnologyCourse.ReservationDate.ToString("yyyy-M-d");

                lblTechCourseExamLab.Text = account.TechnologyCourse.Lab.ToString();

                if (account.TechnologyCourse.Period != 0)
                    lblTechCourseExamPeriod.Text = account.TechnologyCourse.Period.ToString();

                lblTechCourseTestDate.Text = account.TechnologyCourse.ExamDate.ToString("yyyy-M-d");

                if (account.TechnologyCourse.Result != 0)
                {
                    lblTechCourseResult.Text = account.TechnologyCourse.Result.ToString("0.0");

                    lblTechCourseGrade.Text = account.TechnologyCourse.Grade.Value;

                    PassTechExam = account.TechnologyCourse.Result > 10;
                }
            }
            else
            {
                btnReservePopup.Visible = account.IsActivated;
            }

            if (account.Courses != null && account.Courses.Count > 0)
            {
                gvCourses.DataSource = account.Courses;
                gvCourses.DataBind();
            }
            switch (account.ConferenceStatusId)
            {
                case 0:
                    lblConferenceStatus.Text = "لم يتم الحجز";
                    break;
                case 1:
                    lblConferenceStatus.Text = "حجز المؤتمر";
                    break;
                case 2:
                    lblConferenceStatus.Text = "أستكمل الحجز";
                    break;
            }
            if (account.ConferenceBookingDate != null)
            {
                lblConferenceBookDate.Text = account.ConferenceBookingDate.Value.ToString("dd-MM-yyyy");
            }
            if (account.ConferenceCompeleteBookingDate != null)
            {
                lblCompeleteConferenceBookDate.Text = account.ConferenceCompeleteBookingDate.Value.ToString("dd-MM-yyyy");
            }

            
        }

        protected void btnLoadAlreadyRegistered_Click(object sender, EventArgs e)
        {

        }


        protected void GvCourses_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                AccountCourse accountCourse = (AccountCourse)e.Row.DataItem;
                var lblGrade = e.Row.FindControl("lblGrade") as Label;
                var lblCourseName = e.Row.FindControl("lblCourseName") as Label;
                var lblCourseLevel = e.Row.FindControl("lblCourseLevel") as Label;
                var examLink = e.Row.FindControl("examLink") as HyperLink;
                if (lblGrade != null)
                {
                    lblGrade.Text = accountCourse.Grade.Value;
                }
                if (lblCourseName != null)
                {
                    lblCourseName.Text = accountCourse.CourseTitle.Value;
                }
                if (lblCourseLevel != null)
                {
                    lblCourseLevel.Text = accountCourse.CourseLevel.Value;
                }
                int atteendenceSum = 0;
                if (accountCourse.Att_1)
                {
                    atteendenceSum++;
                }
                if (accountCourse.Att_2)
                {
                    atteendenceSum++;
                }
                if (accountCourse.Att_3)
                {
                    atteendenceSum++;
                }
                if (accountCourse.Att_4)
                {
                    atteendenceSum++;
                }
                if (accountCourse.Att_5)
                {
                    atteendenceSum++;
                }
                if (accountCourse.Att_6)
                {
                    atteendenceSum++;
                }
                if (accountCourse.Att_7)
                {
                    atteendenceSum++;
                }
                if (examLink != null)
                {
                    examLink.Visible = !(accountCourse.Grade.Id > 0) && atteendenceSum > 2 && PassTechExam && EnableExam;
                    //examLink.Visible = false;
                    examLink.Text = "الأمتحان";
                    //examLink.NavigateUrl = "~/OnlineExam.aspx?cid=" + accountCourse.CourseId;
                    examLink.NavigateUrl = "~/Exam.aspx?cid=" + accountCourse.CourseId;
                }
            }
        }


        protected void BtnLoad_Clicked(object sender, EventArgs e)
        {
            pnlModal_ModalPopupExtender.Show();
        }

        // Technology Handling


        #region TechnologyReservation

        private Control FindControlRecursive(Control rootControl, string controlID)
        {
            if (rootControl.ID == controlID) return rootControl;

            foreach (Control controlToSearch in rootControl.Controls)
            {
                Control controlToReturn = FindControlRecursive(controlToSearch, controlID);
                if (controlToReturn != null) return controlToReturn;
            }
            return null;
        }


        private void ClearCountLabels()
        {
            for (int i = 1; i < 7; i++)
            {
                ((Label)FindControlRecursive(Page, "lblA" + i.ToString() + "State")).Text = "حجز حتى الآن .. 0";
                ((Label)FindControlRecursive(Page, "lblB" + i.ToString() + "State")).Text = "حجز حتى الآن .. 0";
                ((Label)FindControlRecursive(Page, "lblC" + i.ToString() + "State")).Text = "حجز حتى الآن .. 0";
                ((Label)FindControlRecursive(Page, "lblD" + i.ToString() + "State")).Text = "حجز حتى الآن .. 0";

                ((Button)FindControlRecursive(Page, "btnA" + i.ToString())).Enabled =
                ((Button)FindControlRecursive(Page, "btnB" + i.ToString())).Enabled =
                ((Button)FindControlRecursive(Page, "btnC" + i.ToString())).Enabled =
                ((Button)FindControlRecursive(Page, "btnD" + i.ToString())).Enabled = true;
            }
        }


        private void GetExamAttendeesCount(DateTime examDate, int courseId)
        {
            try
            {
                ClearCountLabels();

                DataTable ExamAttendees = Corsat.Library.DataManager.Main.GetExamAttendeesCount(DateTime.Parse(ddlExamDates.SelectedValue), Convert.ToInt32(ddlCourseNames.SelectedValue));
                
                // Bind Attendees count for each corresponding cell
                if (ExamAttendees != null && ExamAttendees.Rows.Count > 0)
                {
                    for (int rowIndex = 0; rowIndex < ExamAttendees.Rows.Count; rowIndex++)
                    {
                        Label currentLabel = (Label)FindControlRecursive(Page, "lbl" + ExamAttendees.Rows[rowIndex]["ExamLab"].ToString() + ExamAttendees.Rows[rowIndex]["ExamPeriod"].ToString() + "State");
                        Button currentBtn = (Button)FindControlRecursive(Page, "btn" + ExamAttendees.Rows[rowIndex]["ExamLab"].ToString() + ExamAttendees.Rows[rowIndex]["ExamPeriod"].ToString());
                        //Label currentLabel = (Label)FindControlRecursive(Page, "lblA1State");
                        currentLabel.Text = "حجز حتى الآن .. " + ExamAttendees.Rows[rowIndex]["AttendeesCount"].ToString();


                        int index = rowIndex;
                        int allLabsCount =
                            ExamAttendees.AsEnumerable().Where(x => x["ExamPeriod"].ToString() == ExamAttendees.Rows[index]["ExamPeriod"].ToString()).Sum(
                                y => int.Parse(y["AttendeesCount"].ToString()));


                        int attenCount;
                        //if (int.TryParse(ExamAttendees.Rows[rowIndex]["AttendeesCount"].ToString(), out attenCount) && attenCount > 10)
                        if (allLabsCount >= 10)
                        {
                            currentBtn.Enabled = false;
                        }
                        else
                        {
                            currentBtn.Enabled = true;
                        }
                    }
                }
            }
            catch (Exception exc)
            {

            }
        }




        protected void ddlExamDates_SelectedIndexChanged(object sender, EventArgs e)
        {
            ReloadDaysData();
        }

        protected void ddlCourseNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlExamDates.Items.Clear();
            ddlExamDates.Items.Add(new ListItem("اختر اليوم", ""));
            if (string.IsNullOrWhiteSpace(ddlCourseNames.SelectedValue) || Convert.ToInt32(ddlCourseNames.SelectedValue) == 0)
            {
                ClearCountLabels();
                pnlModal_ModalPopupExtender.Show();
                return;
            }
            int techCourseId = Convert.ToInt32(ddlCourseNames.SelectedValue);
            if (techCourseId == (int)TechnologyCourse.Introduction || techCourseId == (int)TechnologyCourse.WindowsAndVideoStudio || techCourseId == (int)TechnologyCourse.Photoshop)
            {
                ddlExamDates.Items.Add(new ListItem(" الجمعة - " + "25 يوليو", "7/25/2014"));
                ddlExamDates.Items.Add(new ListItem(" السبت - " + "26 يوليو", "7/26/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأحد - " + "27 يوليو", "7/27/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأثنين - " + "28 يوليو", "7/28/2014"));
                ddlExamDates.Items.Add(new ListItem(" الثلاثاء - " + "29 يوليو", "7/29/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأربعاء - " + "30 يوليو", "7/30/2014"));
                ddlExamDates.Items.Add(new ListItem(" الجمعة - " + "1 أغسطس", "8/1/2014"));
            }
            else
            {
                ddlExamDates.Items.Add(new ListItem(" السبت - " + "2 أغسطس", "8/2/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأحد - " + "3 أغسطس", "8/3/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأثنين - " + "4 أغسطس", "8/4/2014"));
                ddlExamDates.Items.Add(new ListItem(" الثلاثاء - " + "5 أغسطس", "8/5/2014"));
                ddlExamDates.Items.Add(new ListItem(" الأربعاء - " + "6 أغسطس", "8/6/2014"));
                ddlExamDates.Items.Add(new ListItem(" الخميس - " + "7 أغسطس", "8/7/2014"));
                ddlExamDates.Items.Add(new ListItem(" الجمعة - " + "8 أغسطس", "8/8/2014"));
            }
            /*ddlExamDates.Items.Add(new ListItem("26 يوليو", "7/26/2013"));
            ddlExamDates.Items.Add(new ListItem("27 يوليو", "7/27/2013"));
            ddlExamDates.Items.Add(new ListItem("28 يوليو", "7/28/2013"));
            ddlExamDates.Items.Add(new ListItem("29 يوليو", "7/29/2013"));
            ddlExamDates.Items.Add(new ListItem("30 يوليو", "7/30/2013"));
            ddlExamDates.Items.Add(new ListItem("31 يوليو", "7/31/2013"));
            ddlExamDates.Items.Add(new ListItem("2 أغسطس", "8/2/2013"));
            ddlExamDates.Items.Add(new ListItem("3 أغسطس", "8/3/2013"));
            ddlExamDates.Items.Add(new ListItem("4 أغسطس", "8/4/2013"));
            ddlExamDates.Items.Add(new ListItem("5 أغسطس", "8/5/2013"));
            ddlExamDates.Items.Add(new ListItem("6 أغسطس", "8/6/2013"));
            ddlExamDates.Items.Add(new ListItem("7 أغسطس", "8/7/2013"));
            ddlExamDates.Items.Add(new ListItem("8 أغسطس", "8/8/2013"));
            ddlExamDates.Items.Add(new ListItem("9 أغسطس", "8/9/2013"));*/

            pnlModal_ModalPopupExtender.Show();
        }

        private void ReloadDaysData()
        {
            if (ddlCourseNames.SelectedValue == null || Convert.ToInt32(ddlCourseNames.SelectedValue) == 0 ||
                string.IsNullOrWhiteSpace(ddlExamDates.SelectedValue))
                ClearCountLabels();
            else
                GetExamAttendeesCount(DateTime.Parse(ddlExamDates.SelectedValue), Convert.ToInt32(ddlCourseNames.SelectedValue));

            pnlModal_ModalPopupExtender.Show();
        }

        private void GetCourseButtonDetails(string buttonName)
        {
            string strLab = buttonName.Substring(3, 1);
            string strPeriod = buttonName.Substring(4, 1);
            //ShowPopUpMsg(String.Format("Lab: {0} , Period {1}", strLab, strPeriod));

            //pnlModal_ModalPopupExtender.Show();
        }

        protected void ReserveCourse(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ddlCourseNames.SelectedValue) || Convert.ToInt32(ddlCourseNames.SelectedValue) == 0 ||
            string.IsNullOrWhiteSpace(ddlExamDates.SelectedValue))
            {
                ClearCountLabels();

                pnlModal_ModalPopupExtender.Show();
                return;
            }
            if (AccountId > 0)
            {
                try
                {


                    // Get Call button Id
                    Button b = (Button)sender;
                    //GetCourseButtonDetails(b.ID);
                    var buttonName = b.ID;
                    string strLab = buttonName.Substring(3, 1);
                    string strPeriod = buttonName.Substring(4, 1);


                    TechnologyCourseReservation reservation = new TechnologyCourseReservation();

                    reservation.Lab = strLab.First();
                    reservation.Period = Convert.ToInt32(strPeriod);

                    reservation.ExamDate = DateTime.Parse(ddlExamDates.SelectedValue);

                    Item account = new Item();
                    account.Id = AccountId;
                    reservation.Account = account;

                    Item course = new Item();
                    course.Id = Convert.ToInt32(ddlCourseNames.SelectedValue);
                    course.Value = ddlCourseNames.SelectedItem.Text;
                    reservation.Course = course;


                    Main.ReserveTechnologyCourse(reservation);
                    ReloadDaysData();
                    LoadAccount();

                    lblMessageData.Text = "كورس " + course.Value + " يوم" + ddlExamDates.SelectedItem.Text +
                                          " معمل " + reservation.Lab + " فترة " + reservation.Period;
                    //string courseCode = string.Empty;
                    //switch (course.Id)
                    //{
                    //    case (int)TechnologyCourse.Introduction:
                    //        courseCode = "O";
                    //        break;

                    //    case (int)TechnologyCourse.Powerpoint:
                    //        courseCode = "P";
                    //        break;
                    //    case (int)TechnologyCourse.AutoplayMenuDesigner:
                    //        courseCode = "A";
                    //        break;
                    //    case (int)TechnologyCourse.WindowsAndVideoStudio:
                    //        courseCode = "B";
                    //        break;
                    //    case (int)TechnologyCourse.Photoshop:
                    //        courseCode = "C";
                    //        break;
                    //    case (int)TechnologyCourse.Facebook:
                    //        courseCode = "D";
                    //        break;
                    //}
                    //lblTechReserveCode.Text = courseCode + reservation.ExamDate.Day + reservation.Lab + reservation.Period;
                    //lblMessageData.Text = 

                    pnlModal_ModalPopupExtender.Show();
                    programmaticModalPopup_RegistrationResult.Show();
                }

                catch (Exception)
                {
                }
            }
        }



        #endregion

    }
}